"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.WebLayout = void 0;
exports.useIsReady = useIsReady;
exports.useReady = void 0;

var _react = _interopRequireWildcard(require("react"));

var _classnames = _interopRequireDefault(require("classnames"));

var _useDefault3 = require("../../../utils/hooks/useDefault");

var _webUtils = require("./web-utils");

var _get = require("../../../utils/get");

var _configContext = require("../../../extends/configContext");

var _report = require("../../../utils/report");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

/**
 * 兼容 useReady
 */
var useReady = function useReady(fn) {
  (0, _react.useEffect)(function () {
    fn();
  }, []);
};

exports.useReady = useReady;

function useIsReady() {
  var _useState = (0, _react.useState)(false),
      _useState2 = _slicedToArray(_useState, 2),
      ready = _useState2[0],
      setReady = _useState2[1];

  useReady(function () {
    return setReady(true);
  });
  return ready;
}

var WebLayout = function WebLayout(props) {
  var children = props.children,
      _props$placement = props.placement,
      placement = _props$placement === void 0 ? 'top' : _props$placement,
      _props$scrollable = props.scrollable,
      scrollable = _props$scrollable === void 0 ? 'true' : _props$scrollable,
      tabBarExtraContent = props.tabBarExtraContent,
      className = props.className,
      style = props.style,
      _props$type = props.type,
      type = _props$type === void 0 ? 'card' : _props$type;
  (0, _report.useReport)({
    componentName: 'tab'
  });

  var _useConfig = (0, _configContext.useConfig)(),
      clsPrefix = _useConfig.clsPrefix;

  var tabs = (0, _react.useMemo)(function () {
    return Array.isArray(children) ? children : [children];
  }, [children]);

  var _useDefault = (0, _useDefault3.useDefault)(props.activeId, props.defaultActiveId || (tabs[0] ? tabs[0].props.id : undefined), props.onActive),
      _useDefault2 = _slicedToArray(_useDefault, 2),
      activeId = _useDefault2[0],
      setActiveId = _useDefault2[1];

  var activeIndex = tabs.findIndex(function (x) {
    return x.props.id === activeId;
  });
  var startPosition = (0, _react.useRef)(0); // 在 activeId 变更之后，要更新 TabsBar 的滚动位置

  var ready = useIsReady();

  var _useState3 = (0, _react.useState)([0, 0]),
      _useState4 = _slicedToArray(_useState3, 2),
      _useState4$ = _slicedToArray(_useState4[0], 2),
      scrollLeft = _useState4$[0],
      scrollTop = _useState4$[1],
      setScrollingPosition = _useState4[1];

  var tabBarRef = (0, _react.useRef)(null); // 阻止左右滑动带动全局滑动的问题

  (0, _react.useEffect)(function () {
    if (tabBarRef.current) {
      tabBarRef.current.addEventListener('touchmove', function (event) {
        event.preventDefault(); // 阻止浏览器的默认事件
      });
    }
  }, []);
  var updateScrollingPosition = (0, _react.useCallback)( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
    var _yield$getRect, _yield$getRect2, scrollRect, tabRects, tabRect, size, offset, scrolling, tabRectsWidth;

    return regeneratorRuntime.wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            if (ready) {
              _context.next = 2;
              break;
            }

            return _context.abrupt("return");

          case 2:
            if (scrollable) {
              _context.next = 4;
              break;
            }

            return _context.abrupt("return");

          case 4:
            _context.next = 6;
            return (0, _webUtils.getRect)(tabBarRef, '.dzq-tabs__scroll');

          case 6:
            _yield$getRect = _context.sent;
            _yield$getRect2 = _slicedToArray(_yield$getRect, 1);
            scrollRect = _yield$getRect2[0];
            _context.next = 11;
            return (0, _webUtils.getRect)(tabBarRef, '.dzq-tabs__item');

          case 11:
            tabRects = _context.sent;

            if (!(activeIndex === -1 || !scrollRect || !tabRects[activeIndex])) {
              _context.next = 14;
              break;
            }

            return _context.abrupt("return");

          case 14:
            tabRect = tabRects[activeIndex];
            size = 'width';
            offset = tabRects.slice(0, activeIndex).reduce(function (prev, curr) {
              return prev + curr[size];
            }, 0);
            scrolling = offset - (scrollRect[size] - tabRect[size]) / 2;
            tabRectsWidth = tabRects.reduce(function (prev, curr) {
              return prev + curr[size];
            }, 0);

            if (!(tabRectsWidth < scrollRect.width)) {
              _context.next = 21;
              break;
            }

            return _context.abrupt("return");

          case 21:
            if (!(scrolling <= 0)) {
              _context.next = 24;
              break;
            }

            setScrollingPosition([0, 0]);
            return _context.abrupt("return");

          case 24:
            if (!(scrolling >= tabRectsWidth - scrollRect.width)) {
              _context.next = 27;
              break;
            }

            setScrollingPosition([tabRectsWidth - scrollRect.width, 0]);
            return _context.abrupt("return");

          case 27:
            setScrollingPosition([scrolling, 0]);

          case 28:
          case "end":
            return _context.stop();
        }
      }
    }, _callee);
  })), [activeIndex, ready, scrollable]);
  (0, _react.useEffect)(function () {
    if (ready) {
      updateScrollingPosition();
    }
  }, [ready, updateScrollingPosition]);

  var handleTouchStart = function handleTouchStart(e) {
    e.persist();
    if (!scrollable) return;
    startPosition.current = (0, _get.get)(e, 'touches[0].clientX');
  };

  var handleTouchMove = /*#__PURE__*/function () {
    var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(e) {
      var _yield$getRect3, _yield$getRect4, scrollRect, tabRects;

      return regeneratorRuntime.wrap(function _callee2$(_context2) {
        while (1) {
          switch (_context2.prev = _context2.next) {
            case 0:
              e.persist();

              if (scrollable) {
                _context2.next = 3;
                break;
              }

              return _context2.abrupt("return");

            case 3:
              _context2.next = 5;
              return (0, _webUtils.getRect)(tabBarRef, '.dzq-tabs__scroll');

            case 5:
              _yield$getRect3 = _context2.sent;
              _yield$getRect4 = _slicedToArray(_yield$getRect3, 1);
              scrollRect = _yield$getRect4[0];
              _context2.next = 10;
              return (0, _webUtils.getRect)(tabBarRef, '.dzq-tabs__item');

            case 10:
              tabRects = _context2.sent;
              setScrollingPosition(function (_ref3) {
                var _ref4 = _slicedToArray(_ref3, 1),
                    currentX = _ref4[0];

                var changedPosition = (0, _get.get)(e, 'touches[0].clientX') - startPosition.current;
                startPosition.current = (0, _get.get)(e, 'touches[0].clientX');
                var nextPosition = currentX - changedPosition * 3;
                var tabRectsWidth = tabRects.reduce(function (prev, curr) {
                  return prev + curr.width;
                }, 0);

                if (nextPosition <= 0) {
                  return [0, 0];
                } else if (nextPosition >= tabRectsWidth - scrollRect.width) {
                  return [tabRectsWidth - scrollRect.width, 0];
                } else {
                  return [nextPosition, 0];
                }
              });

            case 12:
            case "end":
              return _context2.stop();
          }
        }
      }, _callee2);
    }));

    return function handleTouchMove(_x) {
      return _ref2.apply(this, arguments);
    };
  }();

  var placementClassName = "".concat(clsPrefix, "-tabs__placement--").concat(placement);
  return /*#__PURE__*/_react.default.createElement("div", {
    className: (0, _classnames.default)("".concat(clsPrefix, "-tabs"), placementClassName, className),
    style: style
  }, /*#__PURE__*/_react.default.createElement("div", {
    className: (0, _classnames.default)("".concat(clsPrefix, "-tabs__bar"), {
      'is-card': type === 'card'
    }),
    ref: tabBarRef
  }, /*#__PURE__*/_react.default.createElement("div", {
    className: (0, _classnames.default)("".concat(clsPrefix, "-tabs__scroll"), _defineProperty({}, "".concat(clsPrefix, "-tabs__scroll--external"), tabBarExtraContent)),
    onTouchStart: handleTouchStart,
    onTouchMove: handleTouchMove
  }, /*#__PURE__*/_react.default.createElement("div", {
    className: "".concat(clsPrefix, "-tabs__list"),
    style: {
      transform: "translateX(".concat(-scrollLeft, "px)")
    }
  }, tabs.map(function (_ref5) {
    var tab = _ref5.props;
    var activeClassName = tab.id === activeId ? 'is-active' : 'is-inactive';
    return (
      /*#__PURE__*/
      // 选项卡按钮
      _react.default.createElement("div", {
        key: tab.id,
        className: (0, _classnames.default)("".concat(clsPrefix, "-tabs__item"), activeClassName, "".concat(clsPrefix, "-tabs__direction--top"), tab.className),
        style: tab.style,
        onClick: function onClick() {
          setActiveId(tab.id);
        }
      }, /*#__PURE__*/_react.default.createElement("div", {
        className: "".concat(clsPrefix, "-tabs__label")
      }, tab.label))
    );
  }))), tabBarExtraContent && /*#__PURE__*/_react.default.createElement("div", {
    className: "".concat(clsPrefix, "-tabs__external")
  }, tabBarExtraContent)), /*#__PURE__*/_react.default.createElement("div", {
    className: "".concat(clsPrefix, "-tabs__panel")
  }, tabs.map(function (_ref6) {
    var tab = _ref6.props;
    return /*#__PURE__*/_react.default.createElement("div", {
      key: tab.id,
      className: (0, _classnames.default)("".concat(clsPrefix, "-tabs__content"), tab.id === activeId ? 'is-active' : 'is-inactive')
    }, tab.id === activeId ? tab.children : null);
  })));
};

exports.WebLayout = WebLayout;

function TabPanel(props) {
  return /*#__PURE__*/_react.default.createElement("div", null);
}

WebLayout.TabPanel = TabPanel;